﻿using Basic.FormCollect;
using Basic.FormRemoteModel;
using Basic.FormRemoteModel.Form;
using Basic.FormRemoteModel.Form.Model;
using WeDonekRpc.Client.Interface;

namespace Basic.FormService.RpcEvent
{
    internal class FormTableEvent : IRpcApiService
    {
        private readonly ICustomFormCollect _Form;
        private readonly IPhysicalTableCollect _PhyTable;
        private readonly IQueryTableCollect _QueryTable;
        private readonly ICustomTableCollect _CustomTable;
        private readonly IFormViewCollect _FormView;
        public FormTableEvent ( ICustomFormCollect form,
            IPhysicalTableCollect phyTable,
            IQueryTableCollect queryTable,
            IFormViewCollect formView,
            ICustomTableCollect customTable )
        {
            this._FormView = formView;
            this._Form = form;
            this._PhyTable = phyTable;
            this._QueryTable = queryTable;
            this._CustomTable = customTable;
        }

        public FormTable[] GetFormTable ( GetFormTable obj )
        {
            var form = this._Form.Get(obj.FormId, a => new
            {
                a.FormType,
                a.FormName
            });
            if ( form.FormType == FormType.代理表单 )
            {
                return this._PhyTable.GetsByFormId<FormTable>(obj.FormId, a => new FormTable
                {
                    Id = a.Id,
                    TableLabel = a.TableLabel
                });
            }
            else if ( form.FormType == FormType.物理表单 )
            {
                return this._QueryTable.GetsByFormId(obj.FormId, a => new FormTable
                {
                    Id = a.Id,
                    TableLabel = a.Show
                });
            }
            else if ( form.FormType == FormType.视图 )
            {
                long tableId = this._FormView.Find(obj.FormId, a => a.Id);
                if ( tableId == 0 )
                {
                    return null;
                }
                return new FormTable[]
                {
                    new FormTable
                    {
                        Id = tableId,
                        TableLabel = form.FormName
                    }
                };
            }
            else
            {
                return this._CustomTable.GetsByFormId(obj.FormId, a => new FormTable
                {
                    Id = a.Id,
                    TableLabel = a.Title
                });
            }
        }
    }
}
